package com.lims.util;

import java.io.InputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;

import com.lims.action.base.BaseAction;

/**
 * 封装文件下载动作
 * 
 * @author Libo Du
 * 
 */
public class DownloadFileAction extends BaseAction {

	private static final long serialVersionUID = 1412684925352660762L;

	// 存放下载目录的根目录路径，例如 E:/upload，通过action的配置文件进行设置
	protected String realPath = "";
	// 文件类型，如 image/pjpeg，通过下载URL进行设置
	protected String contentType = "";
	// 文件名 ，如 picture.jpg，通过下载URL进行设置
	protected String filename;
	// 是否需要在服务器上备份的下载资源(对应于生成版权pdf（需要），财务下载excel（不需要备份）)
	protected boolean isNeedSave = true;

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public String getFilename() {
		try {
			return new String(filename.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return filename;
		}
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getContentType() {
		return contentType;
	}

	public void setRealPath(String value) {
		this.realPath = value;
	}

	public InputStream getInputStream() throws Exception {
		// System.out.println("test.............................");
		// System.out.println("come in getInputStream:"+realPath + "/" +
		// fileName);
		if (!isNeedSave) {
			return new java.io.FileInputStream(filename);
		}
		return new java.io.FileInputStream(realPath + "/" + filename);
	}

	public boolean isNeedSave() {
		return isNeedSave;
	}

	public void setNeedSave(boolean isNeedSave) {
		this.isNeedSave = isNeedSave;
	}

	public String execute() throws Exception {
		String realFilePath = realPath + "/" + filename;
		File downFile = new File(realFilePath);
		if (downFile.exists()) {
			return SUCCESS;
		} else
			return INPUT;
	}
}
